<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="3" :lg="4" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="4" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="4" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">型 号</div>
                      <el-input v-model="query.spec" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="4" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">品 牌</div>
                      <el-input v-model="query.brand" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="4" :sm="6">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, statusIndex) in theStatus" :key="statusIndex" :label="item" :value="statusIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">关键性</div>
                      <el-select v-model="query.weight" placeholder="请选择" size="mini">
                        <el-option v-for="(item, weightIndex) in weight" :key="weightIndex" :label="item" :value="weightIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="2" :md="2" :sm="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler()">新增</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="导出信息采集记录" :visible.sync="dialogTableVisible" width="45%">
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="marginLeft20" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-upload2" size="mini">批量导入</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-printer" size="mini">批量打印二维码</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-row :gutter="10">
        <el-col :span="4">
          <div class="h100vh">
            <el-tabs type="border-card" class="h100vh" :stretch="true">
              <el-tab-pane label="按位置">
                <el-input v-model="filterPositionText" placeholder="输入关键字进行过滤" size="mini" />
                <el-tree ref="positionTree" class="filter-tree" :data="PositionTree" :props="defaultProps" :default-expand-all="false" :filter-node-method="filterPositionNode" :expand-on-click-node="false" @node-click="PositionClick" />
              </el-tab-pane>
              <el-tab-pane label="按分类">
                <el-input v-model="filterCategoryText" placeholder="输入关键字进行过滤" size="mini" />
                <el-tree ref="categoryTree" class="filter-tree" :data="CategoryTree" :props="defaultProps" :default-expand-all="false" :filter-node-method="filterCategoryNode" :expand-on-click-node="false" @node-click="CategoryClick" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
        <el-col :span="20">
          <el-table v-loading="loading" :data="eqList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
            <el-table-column type="index" min-width="50%" label="序号" align="center" />
            <el-table-column type="selection" align="center" min-width="50%" />
            <el-table-column prop="coding" label="设备编号" min-width="90%" align="center" />
            <el-table-column prop="name" label="设备名称" min-width="80%" align="center" />
            <el-table-column prop="spec" label="型号/规格" min-width="90%" align="center" />
            <el-table-column prop="department.name" label="使用部门" min-width="70%" align="center" />
            <el-table-column prop="status" label="状态" align="center" min-width="50%" :formatter="statusFormat" />
            <el-table-column prop="brand" label="品牌" align="center" min-width="90%" />
            <el-table-column prop="install_date" min-width="90%" label="安装日期" align="center" />
            <el-table-column prop="manufacturer.name" label="制造商" min-width="170%" align="center" />
            <el-table-column prop="providers.name" label="供应商" min-width="220%" align="center" />
            <el-table-column v-if="listHandle" fixed="right" label="操作" min-width="150%" align="center">
              <template scope="scope">
                <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="confirmDel(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import API from '@/api/special/equipment'
import { theStatus, weight } from '@/utils/options'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getStatusFormat'],
  components: {
  },
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '名称', '品牌', '型号', '成本中心', '属性', '关键性', '资产性质', '第一级资产', '可替换编号', '状态', '供应商', '制造商', '出厂编号', '所属车间', '所属生产线', '所属工位', '组织', '部门', '分类', '维护负责人', '电话'],
      loading: false,
      filterPositionText: '',
      filterCategoryText: '',
      CategoryTree: [],
      PositionTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      eqList: [],
      theStatus,
      weight,
      total: 0,
      query: { page: 1, limit: 15 },
      selection: []
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  watch: {
    filterPositionText(val) {
      this.$refs.positionTree.filter(val)
    },
    filterCategoryText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    console.log(query)
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
    this.tree()
  },
  methods: {
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    filterPositionNode(value, PositionTree) {
      if (!value) return true
      return PositionTree.name.indexOf(value) !== -1
    },
    filterCategoryNode(value, CategoryTree) {
      if (!value) return true
      return CategoryTree.name.indexOf(value) !== -1
    },
    index() {
      this.loading = true
      API.eqList(this.query).then(response => {
        this.total = response.data.total
        this.eqList = response.data.data
        console.log(this.eqList)
      }).finally(() => {
        this.loading = false
      })
    },
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.$message.error('请选择要到导出的数据')
        return false
      }
      this.selection.forEach((item) => {
        if (item.status === 0) {
          item.statusOut = '测试'
        } else if (item.status === 1) {
          item.statusOut = '启用'
        } else if (item.status === 2) {
          item.statusOut = '临时移除'
        } else if (item.status === 3) {
          item.statusOut = '停用'
        }
        if (item.type === 0) {
          item.typeOut = '系统'
        } else {
          item.typeOut = '自定义'
        }
        if (item.parent) {
          item.parentOut = item.parent.name
        } else {
          item.parentOut = '顶级分类'
        }
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'name': '名称',
        'brand': '品牌',
        'spec': '型号',
        'cost.coding': '成本中心',
        'attribute': '属性',
        'weight': '关键性',
        'fun': '资产性质',
        'parentOut': '第一级资产',
        'replace_coding': '可替换编号',
        'statusOut': '状态',
        'provider.name': '供应商',
        'manufacturer.name': '制造商',
        'serialize': '出厂编号',
        'workshop': '所属车间',
        'line': '所属生产线',
        'process': '所属工位',
        'org.name': '组织',
        'department.name': '部门',
        'category.name': '分类',
        'admin.name': '维护负责人',
        'admin.phone': '电话'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['specialEquipment'],
          Sheets: {
            'specialEquipment': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '特种设备数据.xlsx')
      }
    },
    remove() {
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      this.delOne(API, id, false)
    },
    tree() {
      API.categoryTree().then(response => {
        this.CategoryTree = response.data
      })
      API.positionTree().then(response => {
        this.PositionTree = response.data
      })
    },
    PositionClick(v) {
      const position = {
        position_id: v.id
      }
      API.eqList(position).then(response => {
        this.total = response.data.total
        this.eqList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    CategoryClick(v) {
      const category = {
        category_id: v.id
      }
      API.eqList(category).then(response => {
        this.total = response.data.total
        this.eqList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    addHandler() {
      this.goUrl('/special/equipment/equipment_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/special/equipment/equipment_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      return this.getStatusFormat(row)
    }
  }
}
</script>
<style>
.filter-tree{
  margin-top: 10px;
}
</style>
